const express = require('express');
const { Ollama } = require('@langchain/ollama');
const ResultWrapper = require('../../utils/resultWrapper');

const router = express.Router();

// 初始化 Ollama 客户端
const ollama = new Ollama({
  baseUrl: process.env.OLLAMA_BASE_URL || 'http://localhost:11434',
  model: 'llama2'
});

// 获取可用模型列表
router.get('/models', async (req, res) => {
  try {
    const response = await fetch(`${ollama.baseUrl}/api/tags`);
    const data = await response.json();
    
    res.json(ResultWrapper.success(data.models));
  } catch (error) {
    res.status(500).json(ResultWrapper.error('服务器内部错误'));
  }
});

// 获取特定模型信息
router.get('/models/:modelName', async (req, res) => {
  try {
    const { modelName } = req.params;
    const response = await fetch(`${ollama.baseUrl}/api/show`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ name: modelName }),
    });
    
    const data = await response.json();
    res.json(data);
  } catch (error) {
    res.status(500).json(ResultWrapper.error('服务器内部错误'));
  }
});

// 检查模型状态
router.get('/models/:modelName/status', async (req, res) => {
  try {
    const { modelName } = req.params;
    const response = await fetch(`${ollama.baseUrl}/api/show`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ name: modelName }),
    });
    
    if (response.ok) {
      res.json({ status: 'available' });
    } else {
      res.json({ status: 'unavailable' });
    }
  } catch (error) {
    res.status(500).json(ResultWrapper.error('服务器内部错误'));
  }
});

module.exports = router;